package com.fingard.dsp.bank.directbank.icbc41;

import java.util.*;

import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

public class ICBC41Base extends DirectBase implements ITcpClient {

    public Map<String, String> md5Map = new TreeMap<String, String>();//TreeMap默认是升序的

    protected String getCharset() {
        return getBankConfig().getCharset("gbk");
    }

    protected String getCharsetMD5() {
        return getBankConfig().getCharset("utf-8", "md5");
    }

    protected String getCharsetAuthCheck() {
        return getBankConfig().getCharset("utf-8", "authcheck");
    }

    protected void writeCommonHeader(ICBC41Header p_bankHeader, XmlTextWriter xmlWriter) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.tx_code)) {
            throw new Exception("未赋值TX_CODE");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.seq)) {
            throw new Exception("未赋值SEQ");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.sysid)) {
            throw new Exception("未赋值SYSID");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xmlWriter.writeStartElement("TXN");
        xmlWriter.writeStartElement("HEAD");
        xmlWriter.writeElementString("SEQ", p_bankHeader.seq);//交易序列号
        md5Map.put("SEQ", p_bankHeader.seq);
        xmlWriter.writeElementString("SYSID", p_bankHeader.sysid);//系统号
        md5Map.put("SYSID", p_bankHeader.sysid);
        xmlWriter.writeElementString("TX_CODE", p_bankHeader.tx_code);//交易类型
        md5Map.put("TX_CODE", p_bankHeader.tx_code);
        String currentTime = p_bankHeader.tx_time;
        if (StringHelper.isNullOrEmpty(p_bankHeader.tx_time)) {
            currentTime = Format.DateTime14Format.format(new Date());
        }
        xmlWriter.writeElementString("TX_TIME", currentTime);//交易时间
        md5Map.put("TX_TIME", currentTime);
        xmlWriter.writeElementString("MD5", "@@MD5@@");//安全校验串
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("CONTENT");
    }

    private String generateMD5Value() throws Exception {
        StringBuilder tmpMD5Original = new StringBuilder();
        Set<String> keySet = md5Map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            if (!StringHelper.isNullOrEmpty(md5Map.get(key).toString())) {
                tmpMD5Original.append(key + "=" + md5Map.get(key) + "&");
            }
        }
        String md5String = tmpMD5Original.toString();
        md5String = md5String + "key=" + bankFront.loginPasswd;
        WriteBankLogLn("2.生成的MD5原值为：" + md5String);
        md5String = DigestHelper.cryptoMD5RetHexStr(md5String.getBytes(getCharsetMD5())).toUpperCase();
        WriteBankLogLn("2.生成的MD5值为：" + md5String);
        return md5String;

    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        p_reqStr = p_reqStr.replace("@@MD5@@", generateMD5Value());

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        WriteBankLogStep2(p_reqStr);
        // 发银行
        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr.getBytes(getCharset()));
        String[] retStr = new String[]{"", ""};
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            retStr[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
            WriteBankLogStep3(retStr[1]);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
        }
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</TXN>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    protected String convertCertTypeToBank(String p_certType) {
        /* ATS
        0	身份证
        1	户口簿
        2	护照
        3	军官证
        4	士兵证
        5	港澳居民来往内地通行证
        6	台湾同胞来往内地通行证
        7	临时身份证
        8	外国人居留证
        9	警官证
        99	其他证件*/

        /* BANK
        01	身份证
        02	军官证
        03	护照
        04	回乡证
        05	台胞证
        06	警官证
        07	士兵证
        99	其它证件证件编号不足20位后补空格

        */
        if ("0".equals(p_certType)) {
            return "01";
        } else if ("3".equals(p_certType)) {
            return "02";
        } else if ("2".equals(p_certType)) {
            return "03";
        } else if ("6".equals(p_certType)) {
            return "05";
        } else if ("9".equals(p_certType)) {
            return "06";
        } else if ("4".equals(p_certType)) {
            return "07";
        } else {
            return "99";
        }
    }
}
